package com.sztx.pay.center.rpc.interceptor;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;

import com.sztx.pay.center.common.annotation.SlaveQueryAnnotation;
import com.sztx.pay.center.common.util.ConfigUtil;
import com.sztx.se.dataaccess.mysql.source.DataSourceSwitcher;


public class SlaveQueryMethodInterceptor implements MethodInterceptor {

	private final Logger LOG = LoggerFactory.getLogger(getClass());	
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		try {
			SlaveQueryAnnotation slaveQueryAnnotation = AnnotationUtils.findAnnotation(invocation.getMethod(), SlaveQueryAnnotation.class);  
	        if(slaveQueryAnnotation!=null){  
	            //切换从库数据源
	        	LOG.debug("------------当前使用从库进行查询【开始】------------");
	        	DataSourceSwitcher.setDataSourceTypeForceMaster(ConfigUtil.JdbcSlaveKey);
	        }else{
	        	LOG.debug("------------当前使用主库进行查询【开始】------------");
	        }
	        return invocation.proceed();
		} finally{
			//切回默认主库
			LOG.debug("------------切换回主库【结束】------------");
			DataSourceSwitcher.setDataSourceTypeForceMaster(ConfigUtil.JdbcMasterKey);
		}
	}
}
